package cn.sc.allinpay.allfavour.business.cashiersell;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;

import java.math.BigDecimal;
import java.util.List;

import cn.pai.common.listener.OnPromptListener;
import cn.pai.common.utils.AmtUtils;
import cn.pai.mvp.callback.MpCallBack;
import cn.pai.mvp.intervenor.Intervenor;
import cn.pai.mvp.presenter.PaiPresenter;
import cn.sc.allinpay.allfavour.app.Constant;
import cn.sc.allinpay.allfavour.business.common.data.CouponsData;
import cn.sc.allinpay.allfavour.business.common.data.OrderData;
import cn.sc.allinpay.allfavour.business.common.data.OrderResult;
import cn.sc.allinpay.allfavour.business.common.data.PosData;
import cn.sc.allinpay.allfavour.business.common.data.TransRecord;
import cn.sc.allinpay.allfavour.business.main.MainActivity;
import cn.sc.allinpay.allfavour.business.payment.PaymentActivity;
import cn.sc.allinpay.allfavour.module.device.DeviceLogin;
import cn.sc.allinpay.allfavour.module.printer.IPrinter;
import cn.sc.allinpay.allfavour.module.printer.PrintData;
import cn.sc.allinpay.allfavour.module.printer.PrintManager;

/**
 * 收银台 卡券电子钱包核销 presenter
 * author：pany
 * on 2017/12/1 11:27
 */
public class CashierSellPresenter extends PaiPresenter<CashierSellContract.View> implements CashierSellContract.Presenter {
    public static final int REQ_COUPONSDEDUCT = 0x01;//卡券全额抵扣

    private CashierSellModel model = new CashierSellModel();
    private OrderData order;//交易订单对象
    private TransRecord transRecord;
    private IPrinter printer;

    @Override
    protected Intervenor createIntervenor() {
        return new Intervenor() {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                Bundle bundle = view.getBundle();
                order = bundle.getParcelable(Constant.BundleKey.PAY_ORDER);
            }

            @Override
            public void onResume() {
                super.onResume();
                DeviceLogin.login(view.getContext());
            }

            @Override
            public void onPause() {
                super.onPause();
                DeviceLogin.logout();
            }

            @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (Activity.RESULT_OK == resultCode) {
                    if (data != null) {
                        if (REQ_COUPONSDEDUCT == requestCode) {//卡券全额抵扣
                            view.toActivity(MainActivity.class, null);
                            view.finish();
                        }
                    } else {
                        view.toast("交易参数返回为空");
                    }

                } else {
                    if (data != null) {
                        String reson = data.getStringExtra("reason");
                        if (!TextUtils.isEmpty(reson)) {
                            view.toast(reson);
                        } else {
                            view.toast("交易失败");
                        }
                    } else {
                        view.toast("交易失败");
                    }
                }
            }
        };
    }

    @Override
    public void start() {
        if (initData()) {
            initView();
        } else {
            view.finish();
        }
    }

    /**
     * 数据初始化
     *
     * @return
     */
    private boolean initData() {
        if (order == null) {
            view.toast("订单数据不能为空");
            return false;
        }
        return true;
    }

    /**
     * 初始化视图
     */
    private void initView() {
        view.showTransAmt(AmtUtils.formatY(order.getTransAmt()));
        //会员优惠金额
        if (order.getMemberData() != null &&!TextUtils.isEmpty(order.getMemberData().getOilDiscountName())) {
            view.showDiscountAmt(order.getMemberData().getOilDiscountAmt() != null ? AmtUtils.formatNegY(order.getMemberData().getOilDiscountAmt()) : "0.00");
        } else {
            view.showDiscountAmt("0.00");

        }

        //卡券优惠金额
        view.showCouponsAmt(!TextUtils.isEmpty(order.getDisCouponAmt()) ? AmtUtils.formatNegY(order.getDisCouponAmt()) : "0.00");
        List<CouponsData> couponsList = order.getMemberData().getCoupons();
        if (!TextUtils.isEmpty(order.getDisCouponAmt()) && couponsList != null && !couponsList.isEmpty()) {
            for (int i = 0; i < couponsList.size(); i++) {
                CouponsData coupons = couponsList.get(i);
                if (coupons.getUseNumber() == 0 && (coupons.getUseAmt() == null || TextUtils.isEmpty(coupons.getUseAmt()) || BigDecimal.ZERO.compareTo(new BigDecimal(coupons.getUseAmt())) == 0)) {
                } else {
                    if (coupons.isUse()) {
                        if (coupons.getType() == 0) {//金额
                            view.addCouponView(coupons.getCouponName(), coupons.getUseAmt() + coupons.getUnit());
                        } else {
                            view.addCouponView(coupons.getCouponName(), coupons.getUseNumber() + coupons.getUnit());
                        }
                    }
                }

            }
        }
        //电子钱包折扣金额
        view.showEWalletAmt(!TextUtils.isEmpty(order.getDisEWalletAmt()) ? AmtUtils.formatNegY(order.getDisEWalletAmt()) : "0.00");
        view.showPaidAmt(AmtUtils.formatY(order.getPaidAmt()));
    }

    @Override
    public void sellConfirm() {
        view.loading();
        reqSellOrder(new MpCallBack<OrderResult, String>() {
            @Override
            public void onSuccess(final OrderResult orderResult) {
                view.loaded();
                order.setOrderId(orderResult.getOrderNo());
                order.setRetTime(orderResult.getRetTime());
                if (BigDecimal.ZERO.compareTo(new BigDecimal(order.getPaidAmt())) != 0) {//有剩余支付的金额，则继续支付
                    transRecord = createRecord(order, orderResult.getOrderNo(), orderResult.getRetTime(),
                            1, 1);//支付中
                    model.saveTransRecord(transRecord);//保存交易记录
                    view.prompt(false, "抵扣成功，继续支付", new OnPromptListener("确定") {
                        @Override
                        public void onPositive(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(Constant.BundleKey.TRANS_RECORD, transRecord);
                            bundle.putParcelable(Constant.BundleKey.PAY_ORDER, order);
                            view.toActivity(PaymentActivity.class, bundle);
                            view.finish();
                        }
                    });
                } else {
                    //全额抵扣
                    transRecord = createRecord(order, orderResult.getOrderNo(), orderResult.getRetTime(),
                            0, 3);//剩余支付金额为0，则支付成功
                    model.saveTransRecord(transRecord);//保存交易记录
                    view.prompt(false, "抵扣成功，支付完成，打印凭证", new OnPromptListener("确定") {
                        @Override
                        public void onPositive(DialogInterface dialog, int which) {
                            dialog.dismiss();
//                            AllinUtils.callCouponsDeduct(view.getActivity(), order.getOrderId(), order.getTransAmt(), null, null,
//                                    order.getMemberData().getCardNo(), order.getDisCouponAmt(), order.getDisRightsAmt(),
//                                    order.getDisEWalletAmt(), model.getGlobal().getCashierData().getUrlPrefix(), REQ_COUPONSDEDUCT);
                            print();
                        }
                    });
                }
            }

            @Override
            public void onFailure(String response, String message) {
                view.loaded();
                view.prompt(message);
            }
        });
    }

    /**
     * 打印支付摘要
     */
    public void print() {
        //因为onActivityResult回来没有立即执行onResume方法
        DeviceLogin.login(view.getContext());
        view.loading("交易成功，正在打印...");
        PrintData data = new PrintData();
        data.setMerchantName(model.getGlobal().getConfigData().getMerName());
        data.setTerminalId(model.getGlobal().getConfigData().getTerId());
        data.setOperNo(order.getCashierNo());
        data.setOilName(order.getOilName());
        data.setOperName(order.getCashierName());
        data.setOrderId(order.getOrderId());//订单号
        data.setAmt(order.getTransAmt());//订单总金额
        data.setCardNo(order.getMemberData() != null ? order.getMemberData().getCardNo() : null);//会员卡号
        data.setDisRightsAmt(order.getMemberData() != null ? order.getMemberData().getOilDiscountAmt().toString():null);//会员权益优惠
        data.setDisCouponAmt(order.getDisCouponAmt());//卡券使用金额
        data.setDisEWalletAmt(order.getDisEWalletAmt());//电子钱包使用金额
        data.setTime(transRecord.getTransDate() + transRecord.getTransTime());//交易时间
        data.setTransDate(transRecord.getTransDate());
        data.setTransTime(transRecord.getTransTime());
        data.setCouponUrl(model.getGlobal().getCashierData().getUrlPrefix());
        printer = PrintManager.createPrinter(PrintManager.PRINT_CASHIER_FULL, data);
        printer.print(new IPrinter.OnPrintListener() {
            @Override
            public void onStart(int step) {

            }

            @Override
            public void onSuccess(int step) {
                view.loaded();
                view.toast("打印成功");

                PosData posData = new PosData();

                String printCount = order.getPrintCount();
                if (printCount == null) {
                    order.setPrintCount("1");
                } else {
                    printCount = Integer.parseInt(printCount) + 1 + "";
                    order.setPrintCount(printCount);
                }

                transRecord.setOrderData(JSON.toJSONString(order));
                model.updTransRecord(transRecord);


                view.toActivity(MainActivity.class, null);
                view.finish();
            }

            @Override
            public void onFail(int code, String msg) {
                view.loaded();
                view.prompt(false, msg + ",是否继续打印", new OnPromptListener("确定", "取消") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        print();
                    }

                    @Override
                    public void onNegative(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.toActivity(MainActivity.class, null);
                        view.finish();
                    }
                });
            }
        });
    }

    /**
     * 创建交易记录
     *
     * @param orderData 订单数据
     * @param orderId   订单号
     * @param transTime 交易时间
     * @param state     支付状态  0:默认状态 1:支付中 2:支付成功(全单支付完成) 3:撤销中(尚有其他子订单尚未撤销成功的) 4:撤销成功(全单撤销完成)
     * @param sellState 抵扣状态  0:无抵扣(普通交易) 1:抵扣成功  2:抵扣撤销 3:全额抵扣成功 4：全额抵扣撤销
     * @return
     */
    private TransRecord createRecord(OrderData orderData, String orderId, String transTime, int state, int sellState) {
        TransRecord record = new TransRecord();
        record.setTransNo(orderId);//订单id
        record.setOrderId(orderId);//订单id
        record.setTransAmt(order.getTransAmt());//订单交易金额
        record.setPaidAmt(order.getPaidAmt());//支付金额
        record.setDisRightsAmt(order.getMemberData() != null ? order.getMemberData().getOilDiscountAmt().toString():null);//会员优惠金额
        record.setDisCouponAmt(order.getDisCouponAmt());//卡券使用金额
        record.setDisEWalletAmt(order.getDisEWalletAmt());//电子钱包使用金额
        record.setTransDate(transTime.substring(0, 8));//交易日期
        record.setTransTime(transTime.substring(8));//交易时间
        record.setState(state);//订单状态
        record.setSellState(sellState);//销账状态
        record.setOrderData(JSON.toJSONString(orderData));
        return record;
    }

    /**
     * 发起订单核销
     */
    private void reqSellOrder(MpCallBack<OrderResult, String> mpCallBack) {
        model.reqSellOrder(order.getMemberData().getAuthCode(), order.getTransAmt(), order.getDisEWalletAmt(),
                order.getMemberData().getCoupons(), order.getDisCouponAmt(), order.getMemberData().getOilDiscountAmt().toString(), order.getPaidAmt(),order.getOilType(), mpCallBack);
    }
}
